﻿using ProtoBuf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

internal class ProtobufTool
{
    /// <summary>
    /// 编码
    /// </summary>
    /// <param name="msgBase"></param>
    /// <returns></returns>
    public static byte[] Encode(IExtensible msgBase)
    {
        using(var ms = new MemoryStream())
        {
            ProtoBuf.Serializer.Serialize(ms, msgBase);
            return ms.ToArray();
        }
    }

    /// <summary>
    /// 解码
    /// </summary>
    /// <param name="protoName">协议名字</param>
    /// <param name="bytes">字节数组</param>
    /// <param name="offset">数据起始位置</param>
    /// <param name="count">长度</param>
    /// <returns></returns>
    public static IExtensible Decode(string protoName, byte[] bytes, int offset, int count)
    {
        // 反序列化
        using (var ms = new MemoryStream(bytes, offset, count))
        {
            Type type = Type.GetType(protoName);
            return (IExtensible)Serializer.NonGeneric.Deserialize(type, ms);
        }
    }

    /// <summary>
    /// 协议名编码
    /// </summary>
    /// <param name="msgBase"></param>
    /// <returns></returns>
    public static byte[] EncodeName(IExtensible msgBase)
    {
        PropertyInfo info = msgBase.GetType().GetProperty("protoName");

        string s = info.GetValue(msgBase).ToString();

        byte[] nameBytes = Encoding.UTF8.GetBytes(s);

        short len = (short)nameBytes.Length;

        byte[] bytes = new byte[len + 2];

        bytes[0] = (byte)(len & 0x00ff);
        bytes[1] = (byte)(len >> 8);

        Array.Copy(nameBytes, 0, bytes, 2, len);

        return bytes;
    }

    /// <summary>
    /// 协议名 解码
    /// </summary>
    /// <param name="bytes">字节数组</param>
    /// <param name="offset">起始位置</param>
    /// <param name="count">返回的解析长度</param>
    /// <returns></returns>
    public static string DecodeName(byte[] bytes, int offset, out int count)
    {
        count = 0;
        if (offset + 2 > bytes.Length)
        {
            return "";
        }

        short len = (short)(bytes[offset + 1] << 8 | bytes[offset]);

        if (len <= 0)
        {
            return "";
        }

        count = len + 2;

        return Encoding.UTF8.GetString(bytes, offset + 2, len);
    }
}
